LED灯代码:
import RPi.GPIO as GPIO
import time


GPIO.setwarnings(False)  #忽略引脚占用警告
GPIO.setmode(GPIO.BOARD)  #设置引脚模式为BOARD模式（物理引脚）
GPIO.setup(22, GPIO.OUT, initial = GPIO.LOW)  #设置第22号引脚）2为输出模式，初始化为低电平

while True:
	GPIO.output(22, GPIO.HIGH)  #指定22号引脚输出高电平	
	time.sleep(1)  #睡眠1秒
	GPIO.output(22, GPIO.LOW)  #指定22号引脚输出低电平
	time.sleep(1)  #睡眠1秒

舵机：
from time import sleep
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
 
pan = 23
tilt = 24
 
GPIO.setup(tilt, GPIO.OUT) # white => TILT
GPIO.setup(pan, GPIO.OUT) # gray ==> PAN
 
def setServoAngle(servo, angle):
    assert angle >=30 and angle <= 150
    pwm = GPIO.PWM(servo, 50)
    pwm.start(8)
    dutyCycle = angle / 18. + 3.
    pwm.ChangeDutyCycle(dutyCycle)
    sleep(0.3)
    pwm.stop()
 
if __name__ == '__main__':  
    for i in range (30, 160, 15):
        setServoAngle(pan, i)
        setServoAngle(tilt, i)
     
    for i in range (150, 30, -15):
        setServoAngle(pan, i)
        setServoAngle(tilt, i)
         
    setServoAngle(pan, 100)
    setServoAngle(tilt, 90)    
    GPIO.cleanup()
人脸识别：
'''
Haar Cascade Face detection with OpenCV  
    Based on tutorial by pythonprogramming.net
    Visit original post: https://pythonprogramming.net/haar-cascade-face-eye-detection-python-opencv-tutorial/  
Adapted by Marcelo Rovai - MJRoBot.org @ 7Feb2018 
'''

import numpy as np
import cv2

# multiple cascades: https://github.com/Itseez/opencv/tree/master/data/haarcascades
faceCascade = cv2.CascadeClassifier('Cascades/haarcascade_frontalface_default.xml')

cap = cv2.VideoCapture(0)
cap.set(3,640) # set Width
cap.set(4,480) # set Height

while True:
    ret, img = cap.read()
    img = cv2.flip(img, -1)
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    faces = faceCascade.detectMultiScale(
        gray,
        
        scaleFactor=1.2,
        minNeighbors=5
        ,     
        minSize=(20, 20)
    )

    for (x,y,w,h) in faces:
        cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
        roi_gray = gray[y:y+h, x:x+w]
        roi_color = img[y:y+h, x:x+w]
        

    cv2.imshow('video',img)

    k = cv2.waitKey(30) & 0xff
    if k == 27: # press 'ESC' to quit
        break

cap.release()
cv2.destroyAllWindows()
颜色识别：
from collections import deque
from picamera.array import PiRGBArray
from picamera import PiCamera
import time
import cv2
import numpy as np

# 定义颜色上下限，用的是hsv颜色而不是rgb颜色，扩展以包含类似红色的颜色
red_lower1 = np.array([0, 100, 100])
red_upper1 = np.array([10, 255, 255])
red_lower2 = np.array([170, 100, 100])
red_upper2 = np.array([179, 255, 255])

mybuffer = 64
pts = deque(maxlen=mybuffer)

camera = PiCamera()
camera.resolution = (640, 480)
camera.framerate = 32
rawCapture = PiRGBArray(camera, size=(640, 480))

time.sleep(1)
for image in camera.capture_continuous(rawCapture, format="bgr", use_video_port=True):
    frame = image.array
    hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)

    # 创建分别针对低端和高端红色范围的掩码
    mask1 = cv2.inRange(hsv, red_lower1, red_upper1)
    mask2 = cv2.inRange(hsv, red_lower2, red_upper2)
    mask = cv2.bitwise_or(mask1, mask2)

    mask = cv2.erode(mask, None, iterations=2)
    mask = cv2.dilate(mask, None, iterations=2)
    cnts = cv2.findContours(mask.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[-2]

    center = None
    if len(cnts) > 0:
        c = max(cnts, key=cv2.contourArea)
        ((x, y), radius) = cv2.minEnclosingCircle(c)
        M = cv2.moments(c)
        center = (int(M["m10"] / M["m00"]), int(M["m01"] / M["m00"]))
        if radius > 10:
            cv2.circle(frame, (int(x), int(y)), int(radius), (0, 255, 255), 2)
            cv2.circle(frame, center, 5, (0, 0, 255), -1)
            pts.appendleft(center)
    
    for i in range(1, len(pts)):
        if pts[i - 1] is None or pts[i] is None:
            continue
        thickness = int(np.sqrt(mybuffer / float(i + 1)) * 2.5)
        cv2.line(frame, pts[i - 1], pts[i], (0, 0, 255), thickness)

    cv2.imshow("Frame", frame)
    key = cv2.waitKey(1) & 0xFF

    rawCapture.truncate(0)
    
    if key == ord("q"):
        break

cv2.destroyAllWindows()

小车：
from time import sleep
import tkinter as tk
from tkinter import Label
import cv2
from PIL import Image, ImageTk
import RPi.GPIO as GPIO
import time

# 使用BCM编号方式
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)

# 设置小车控制的GPIO端口1-4（根据BCM编号方式）
car_gpio_pins = [11,12 ,13, 15]

# 设置云台舵机的GPIO端口
servo_pins = [23, 24]

# 初始化舵机角度
servo_angles = {servo_pins[0]: 90, servo_pins[1]: 90}

def show_name(func):
    def wrapper(*args, **kwargs):
        print(f"Function '{func.__name__}' is called")
        return func(*args, **kwargs)
    return wrapper

@show_name
def init_car():
    # 将小车控制的GPIO端口设置为输出模式
    for pin in car_gpio_pins:
        GPIO.setup(pin, GPIO.OUT)

@show_name
def stop():
    for pin in car_gpio_pins:
        GPIO.output(pin, GPIO.LOW)


@show_name
def turn_left():
    stop()
    GPIO.output(car_gpio_pins[0], GPIO.HIGH)
    GPIO.output(car_gpio_pins[3], GPIO.HIGH)

@show_name
def turn_right():
    stop()
    GPIO.output(car_gpio_pins[1], GPIO.HIGH)
    GPIO.output(car_gpio_pins[2], GPIO.HIGH)

@show_name
def forward():
    stop()
    GPIO.output(car_gpio_pins[0], GPIO.HIGH)
    GPIO.output(car_gpio_pins[2], GPIO.HIGH)


@show_name
def backward():
    stop()
    GPIO.output(car_gpio_pins[1], GPIO.HIGH)
    GPIO.output(car_gpio_pins[3], GPIO.HIGH)

@show_name
def set_servo_angle(servo, angle):
    GPIO.setup(servo, GPIO.OUT)
    pwm = GPIO.PWM(servo, 50)
    pwm.start(8)
    duty_cycle = angle / 18. + 3.
    pwm.ChangeDutyCycle(duty_cycle)
    sleep(0.3)
    pwm.stop()

def adjust_servo_angle(servo, delta):
    new_angle = servo_angles[servo] + delta
    new_angle = max(0, min(180, new_angle))
    servo_angles[servo] = new_angle
    set_servo_angle(servo, new_angle)


def create_gui():
    root = tk.Tk()
    root.title("Car Control")

    # 创建视频显示标签
    video_label = Label(root)
    video_label.grid(row=0, column=0, columnspan=4)

    # 初始化摄像头
    cap = cv2.VideoCapture(0)

    def update_frame():
        ret, frame = cap.read()
        if ret:
            frame = cv2.flip(frame, -1)
            frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
            img = Image.fromarray(frame)
            imgtk = ImageTk.PhotoImage(image=img)
            video_label.imgtk = imgtk
            video_label.configure(image=imgtk)
        video_label.after(10, update_frame)

    update_frame()

    forward_button = tk.Button(root, text="Forward")
    forward_button.grid(row=1, column=1)
    forward_button.bind('<ButtonPress-1>', lambda event: forward())
    forward_button.bind('<ButtonRelease-1>', lambda event: stop())

    left_button = tk.Button(root, text="Left")
    left_button.grid(row=2, column=0)
    left_button.bind('<ButtonPress-1>', lambda event: turn_left())
    left_button.bind('<ButtonRelease-1>', lambda event: stop())

    stop_button = tk.Button(root, text="Stop")
    stop_button.grid(row=2, column=1)
    stop_button.bind('<ButtonPress-1>', lambda event: stop())

    right_button = tk.Button(root, text="Right")
    right_button.grid(row=2, column=2)
    right_button.bind('<ButtonPress-1>', lambda event: turn_right())
    right_button.bind('<ButtonRelease-1>', lambda event: stop())

    backward_button = tk.Button(root, text="Backward")
    backward_button.grid(row=3, column=1)
    backward_button.bind('<ButtonPress-1>', lambda event: backward())
    backward_button.bind('<ButtonRelease-1>', lambda event: stop())
 
   # 云台控制按钮
    servo_up_button = tk.Button(root, text="Servo Up")
    servo_up_button.grid(row=1, column=3)
    servo_up_button.bind('<ButtonPress-1>', lambda event: adjust_servo_angle(servo_pins[1], -5))

    servo_down_button = tk.Button(root, text="Servo Down")
    servo_down_button.grid(row=3, column=3)
    servo_down_button.bind('<ButtonPress-1>', lambda event: adjust_servo_angle(servo_pins[1], 5))

    servo_left_button = tk.Button(root, text="Servo Left")
    servo_left_button.grid(row=2, column=3)
    servo_left_button.bind('<ButtonPress-1>', lambda event: adjust_servo_angle(servo_pins[0], -5))

    servo_right_button = tk.Button(root, text="Servo Right")
    servo_right_button.grid(row=2, column=4)
    servo_right_button.bind('<ButtonPress-1>', lambda event: adjust_servo_angle(servo_pins[0], 5))

    root.mainloop()
    cap.release()

if __name__ == "__main__":
    init_car()
    create_gui()
    GPIO.cleanup()

 
 
 
